﻿#include "gallop.h"
#include <define.h>
#include "runtime_engine.h"
#include "evaluate_engine.h"
#include "config.h"
#include "factory.h"
#include "time_utils.hpp"




void start_runtime(const char * account_config, const char* strategy_config)
{
	lt::runtime_engine app(account_config);
	auto now = time_to_uint(get_now());
	const auto& config = get_execute_config(strategy_config, now);
	std::map<lt::sigid_t,std::shared_ptr<lt::signal>> signals;
	auto& sig_info = std::get<0>(config);
	for (auto it : sig_info)
	{
		signals[it.id] = make_signal(app, it);
	}
	std::map<lt::trdid_t, std::shared_ptr<lt::trend>> trends;
	auto& trd_info = std::get<1>(config);
	for (auto it : trd_info)
	{
		trends[it.id] = make_trend(app, it);
	}
	app.init(signals, trends);
	auto& stra_info = std::get<2>(config);
	std::map<lt::straid_t, std::shared_ptr<lt::strategy>> strategys ;
	for (auto it : stra_info)
	{
		strategys[it.id] = make_strategy(app,it);
	}
	app.run_to_close(strategys);
	app.destory();
}


void start_evaluate(const char* account_config, const char* strategy_config, const char* trading_day_config)
{
	lt::evaluate_engine app(account_config);

	const auto& trading_day = get_trading_day_config(trading_day_config);
	for(auto& td_it : trading_day)
	{
		const auto& config = get_execute_config(strategy_config, td_it);
		const auto& stra_config = std::get<0>(config);
		auto& sig_info = std::get<0>(config);
		std::map<lt::sigid_t, std::shared_ptr<lt::signal>> signals;
		for (auto it : sig_info)
		{
			signals[it.id] = make_signal(app, it);
		}
		std::map<lt::trdid_t, std::shared_ptr<lt::trend>> trends;
		auto& trd_info = std::get<1>(config);
		for (auto it : trd_info)
		{
			trends[it.id] = make_trend(app, it);
		}
		app.init(signals, trends);
		auto& stra_info = std::get<2>(config);
		std::map<lt::straid_t, std::shared_ptr<lt::strategy>> strategys;
		for (auto it : stra_info)
		{
			strategys[it.id] = make_strategy(app, it);
		}
		app.back_test(strategys, td_it);
		app.destory();
	}
	
}


int main(int argc,char* argv[])
{
	//start_runtime("runtime.ini", "strategy_10w.xml");
	//start_evaluate("evaluate.ini","strategy_10w.xml", "trading_days.xml");
	//return 0;
	if(argc < 4)
	{
		LOG_ERROR("start atgc error");
		return -1;
	}
	if (std::strcmp("evaluate", argv[1]) == 0)
	{
		if (argc < 5)
		{
			LOG_ERROR("start atgc error");
			return -1;
		}
		const char* account_file = argv[2];
		const char* strategy_file = argv[3];
		const char* trading_day_file = argv[4];
		LOG_INFO("start evaluate for %s %s %s\n", account_file, strategy_file, trading_day_file);
		start_evaluate(account_file, strategy_file, trading_day_file);
	}
	else
	{
		if (argc < 4)
		{
			LOG_ERROR("start atgc error");
			return -1;
		}
		const char* account_file = argv[2];
		const char* strategy_file = argv[3];
		LOG_INFO("start runtime for %s %s\n", account_file, strategy_file);
		start_runtime(account_file, strategy_file);
	}
	return 0;
}
